#!/bin/sh

ENV_FOR_ME7=/var/run/swimage/env_for_me7.log
ENV_FOR_SELECT_IMAGE=/var/run/swimage/env_for_select_image.log
#STATUS_FILE="/etc/download_status.txt"
STATUS_FILE="/dev/null"
#DEV_MSG=/dev/console
DEV_MSG=/dev/null

#it should be better update it each time after mib reset

fw_printenv sw_commit sw_tryactive sw_active0_ok sw_active1_ok sw_valid0 sw_valid1 > /var/run/fw_printenv.conf
. /var/run/fw_printenv.conf

logmsg() {
        echo "$1" > $DEV_MSG
        echo "$1" >> $STATUS_FILE
        #logger -p4 -t FIRMWARE "$1"
}

free_mem() {
	echo "" > $DEV_MSG
	echo "$1" > $DEV_MSG
	free > $DEV_MSG
}

on_sighup() {
	logmsg "skip signal"
}

#check if the TX is ready or not
extoam_swdl_tx_ready() {
	local transaction_id
	local on
	transaction_id=`omci -c "extoam sw_dl tx" | grep "Transaction id" | cut -d":" -f 2 | cut -d" " -f 1`
	on=`omci -c "extoam sw_dl tx" | grep "On:" | cut -c5`
	if [ $transaction_id == '0' ] && [ $on == '0' ]; then
		eval "$1='1'"
	else
		eval "$1='0'"
	fi
}

omci_enable() {
	[ -f /nvram/wan.dat ] && . /nvram/wan.dat 
	[ -z "$uplink_type" ] && uplink_type=gpon

	if [ $uplink_type == "gpon" ]; then
		eval "$1='1'"
	else
		eval "$1='0'"
	fi
}

restore_target_diff_from_nvram() {
	local sw_version
	local metafile_nvram_diff
	local basefile
	local merge_tmp
	local rimage_name
	local cimage_name

	if grep "active=1" /proc/cmdline>/dev/null ; then
		#restore image0
		rimage_name="Rimage"
		cimage_name="Cimage"
	else
		#restore image1
		rimage_name="Rimage1"
		cimage_name="Cimage1"
	fi

	[ ! -d /var/run/swimage/$rimage_name ] && mkdir -p /var/run/swimage/$rimage_name

	merge_tmp="/var/run/swimage/merge.$$"
	if mount -t squashfs /dev/mtdblock/`/bin/grep -i \"$rimage_name\" /proc/mtd|cut -c4` /var/run/swimage/$rimage_name/ -o ro; then
		sw_version=`sed -n -e '/^version=/s/version=//p' /var/run/swimage/$rimage_name/root/version`                      
		cp /var/run/swimage/$rimage_name/etc/wwwctrl/metafile.dat /var/metafile.dat	#file need to keep
		umount /var/run/swimage/$rimage_name/ > /dev/null 2>&1                                                         
	fi

	if [ "$sw_version" = "" ]; then
		metafile_nvram_diff="/nvram/metafile.version/metafile.null_version"
	else
		metafile_nvram_diff="/nvram/metafile.version/metafile.$sw_version"
	fi

	if [ -s "$metafile_nvram_diff" ]; then
		basefile="/var/metafile.dat"
		logmsg "found $metafile_nvram_diff, kvmerge_update_only to metafile"
		/opt/httpd/data/cgi-bin/wwwctrl.cgi --kvmerge_update_only $basefile $metafile_nvram_diff > $merge_tmp

		# write back merge_tmp to targe image
		[ ! -d /var/run/swimage/$cimage_name ] && mkdir -p /var/run/swimage/$cimage_name

		### in rc assume cimage only ubifs or jffs2
		if cat /proc/filesystems | grep ubi; then
			/usr/sbin/ubi_mount.sh "$cimage_name" /var/run/swimage/$cimage_name > /dev/null 2>&1
		else
			mtd_num=`/bin/grep -iw "\"$cimage_name\"" /proc/mtd|cut -d: -f1|cut -c4-|head -1`
			mount -t jffs2 /dev/mtdblock/$mtd_num /var/run/swimage/$cimage_name -o rw
		fi

		if [ $? = 0 ]; then
			### file in $cimage_name we want to keep
			targetfile=/var/run/swimage/$cimage_name/etc/wwwctrl/metafile.dat
			# write back files to $cimage_name
			mv $merge_tmp $targetfile 
		fi
		sync;sync
		umount /var/run/swimage/$cimage_name/ > /dev/null 2>&1
	fi
	return 0
}

trap on_sighup SIGHUP

[ ! -d /var/run/swimage ] && mkdir /var/run/swimage/

case $1 in
	start_download)
			#echo mode 0 > /proc/qoshook 	#(0:si>rt>np, 1:rt>si>np, 2:rt>np>si
			sync && echo 3 >/proc/sys/vm/drop_caches
			free_mem "Start Software Download"
			echo 1 > /tmp/led_sw_upgrade # slow blink
			;;
	end_download)
			local err; err=0
			
			mv $2 $2.$$
			logmsg "update image_name $2.$$ instance $3" 
			[ -f /usr/bin/logger ] && logger -p4 -t FIRMWARE "update image_name $2.$$ instance $3"
			cd /
			#..../script/sw_download.sh end_download /var/run/swimage/swimage.bin 0
			#echo mode 1 > /proc/qoshook 	#(0:si>rt>np, 1:rt>si>np, 2:rt>np>si

			[ ! -d /var/mountimg ] && mkdir /var/mountimg
			[ -f $ENV_FOR_ME7 ] && rm -f $ENV_FOR_ME7

			sync && echo 3 >/proc/sys/vm/drop_caches
			free_mem "before remove header"	
			if ! makebin -r $2.$$; then
				logmsg "Image can't find header $2.$$ "
			fi
	
			sync && echo 3 >/proc/sys/vm/drop_caches
			free_mem "after remove header; before mount"	
			mount -o loop -r -t squashfs $2.$$ /var/mountimg
			if [ "$?" = "0" ]; then

				omci_enable omci_en  

				if [ $omci_en = "1" ]; then
					local extoam_enable=0
					extoam_enable=`omci -c "env extoam_enable" | sed -n '/^[0-9]/p'`
					extoam_swdl_tx_ready result
					if [ $extoam_enable = "1" ] && [ $result = "1" ]; then
						local itas_image
						local transaction_id
						local on

						itas_image=`omci -c "env extoam_itas_image_name" | sed -n '/^itas/p'`
						cp -f /var/mountimg/$itas_image /tmp
						err=$?
						if [ $err != "0" ]; then
							logmsg "Fail to copy itas image to /tmp" 
						else
							omci -c "extoam event 2"
						fi
						local START=`date +%s`
						local end=0
						while [ $(( $(date +%s) - 60 )) -lt $START ]; do #PMC firmware update at most 30 seconds.
							sleep 1
							transaction_id=`omci -c "extoam sw_dl tx" | grep "Transaction id" | cut -d":" -f 2 | cut -d" " -f 1`
							on=`omci -c "extoam sw_dl tx" | grep "On:" | cut -c5`
							if [ $transaction_id = '0' ] || [ $on = '0' ]; then
								end=1
								break
							fi
						done
						if [ $end == 0 ]; then
							logmsg "PMC firmware update failure."
							exit $err
						fi
					fi
				fi

				$err=0
				sync && echo 3 >/proc/sys/vm/drop_caches
				free_mem "after mount"	
				echo 2 > /tmp/led_sw_upgrade # fast blink
				sh -x /var/mountimg/start_install.sh $3
				err=$?
				sync && echo 3 >/proc/sys/vm/drop_caches
				free_mem "after update"	
				cd /
				umount /dev/loop0 > /dev/null 2>&1
				umount /dev/loop1 > /dev/null 2>&1
				losetup -d /dev/loop0 > /dev/null 2>&1
				losetup -d /dev/loop1 > /dev/null 2>&1
				umount -df /var/mountimg/ > /dev/null 2>&1
				#ps > /dev/console
				rm -r /var/mountimg
				sync && echo 3 >/proc/sys/vm/drop_caches
				free_mem "after update and umount"	
				rm -f $2.$$
				rm -f $ENV_FOR_ME7
				restore_target_diff_from_nvram

				if [ "$err" != "0" ]; then
					logmsg "firmware upgrade error" 
        				[ -f /usr/bin/logger ] && logger -p4 -t FIRMWARE "firmware upgrade error"
					echo 3 > /tmp/led_sw_upgrade # alarm on
				else
					logmsg "firmware upgrade success" 
        				[ -f /usr/bin/logger ] && logger -p4 -t FIRMWARE "firmware upgrade success"
					echo 0 > /tmp/led_sw_upgrade # off
					
					if [ -f /root/version ] ; then
						cp /root/version /tmp/upgrade_image
						/usr/sbin/upgrade_history update
					fi
				fi
				exit "$err"
			else
				logmsg "firmware upgrade mount image error" 
				[ -f /usr/bin/logger ] && logger -p4 -t FIRMWARE "firmware upgrade mount image error"
				rm -f $2.$$
				rm -r /var/mountimg
				echo 3 > /tmp/led_sw_upgrade # alarm on
				exit 1
			fi
			;;
	activate)
			logmsg "activate instance $2.$$"
			logmsg "wait message response"
			(usleep 10000; reboot) &
			;;
	commit)         
			logmsg "commit instance $2.$$"
			[ -f $ENV_FOR_ME7 ] && rm -f $ENV_FOR_ME7
			;;
	dump_env)         
			if [ -f $ENV_FOR_ME7 ]; then
				#don't need to read again
				exit 0
			fi

			logmsg "dump uboot env parameter and rimage version"

			fw_printenv sw_commit sw_tryactive sw_active0_ok sw_active1_ok sw_valid0 sw_valid1 > $ENV_FOR_SELECT_IMAGE
			. $ENV_FOR_SELECT_IMAGE
			
			active=$sw_tryactive
			if [ "$active" = "2" ]; then
				if grep "active=1" /proc/cmdline>/dev/null ; then
					active=1
				else
					active=0
				fi
			fi

			#if [ -f /etc/custom_version ]; then
			#	. /etc/custom_version
			#else
				version=`sed -n -e '/^version=/s/version=//p' /root/version`
			#fi

			if [ "$active" = "0" ]; then
				sw_version0=$version
				sw_version1="NULLSTR"
				if [ "$sw_valid1" = "1" ]; then
					[ ! -d /var/run/swimage/Rimage1 ] && mkdir /var/run/swimage/Rimage1
					if [ "$sw_version1" = "NULLSTR" ]; then
						if mount -t squashfs /dev/mtdblock/`/bin/grep -i '"Rimage1"' /proc/mtd|cut -c4` /var/run/swimage/Rimage1/ -o ro; then
							#. /var/run/swimage/Rimage1/root/version	#default version
							version=`sed -n -e '/^version=/s/version=//p' /var/run/swimage/Rimage1/root/version`
							sw_version1=$version
							umount /var/run/swimage/Rimage1/ > /dev/null 2>&1
						fi
					fi
				fi

			elif [ "$active" = "1" ]; then
				sw_version1=$version
				sw_version0="NULLSTR"
				if [ "$sw_valid0" = "1" ]; then
					[ ! -d /var/run/swimage/Rimage0 ] && mkdir /var/run/swimage/Rimage0
					if [ "$sw_version0" = "NULLSTR" ]; then
						if mount -t squashfs /dev/mtdblock/`/bin/grep -i '"Rimage"' /proc/mtd|cut -c4` /var/run/swimage/Rimage0/ -o ro; then
							#. /var/run/swimage/Rimage0/root/version	#default version
							version=`sed -n -e '/^version=/s/version=//p' /var/run/swimage/Rimage0/root/version`
							sw_version0=$version	
							umount /var/run/swimage/Rimage0/ > /dev/null 2>&1
						fi
					fi
				fi
			fi

			cat > $ENV_FOR_ME7 << EOF
sw_tryactive=$active
sw_commit=$sw_commit
sw_active0_ok=$sw_active0_ok
sw_active1_ok=$sw_active1_ok
sw_valid0=$sw_valid0
sw_valid1=$sw_valid1
sw_version0=$sw_version0
sw_version1=$sw_version1
EOF
			;;
	*)             
			logmsg "Error parameter" 
			exit -1
			;;
esac



exit 0
